<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use App\Models\SystemLog;
use Illuminate\Support\Facades\Log;

class FileController extends Controller
{
    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request)
    {
        // 验证文件
        $request->validate([
            'avatar' => 'required|file|image|mimes:jpeg,png,jpg,gif|max:2048'
        ], [
            'avatar.required' => '请选择要上传的头像文件',
            'avatar.file' => '上传的不是有效的文件',
            'avatar.image' => '文件必须是图片格式',
            'avatar.mimes' => '只支持 jpeg, png, jpg, gif 格式的图片',
            'avatar.max' => '图片大小不能超过 2MB'
        ]);

        $user = $request->user();
        
        try {
            // 删除旧头像
            if ($user->avatar) {
                $this->deleteOldAvatar($user->avatar);
            }

            // 上传新头像到专门的avatars目录
            $file = $request->file('avatar');
            $fileName = 'avatar_' . $user->id . '_' . time() . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('avatars', $fileName, 'local');

            // 生成访问URL（通过专门的访问路由）
            $avatarUrl = '/api/files/avatar/' . $fileName;

            // 更新用户头像
            $user->update([
                'avatar' => $avatarUrl
            ]);

            // 记录上传日志
            SystemLog::log(
                'upload_avatar',
                'file',
                '用户上传头像',
                $user->id,
                'User',
                $user->id,
                null,
                ['file_name' => $fileName, 'file_size' => $file->getSize()],
                'info'
            );

            return response()->json([
                'success' => true,
                'message' => '头像上传成功',
                'data' => [
                    'avatar_url' => $avatarUrl,
                    'file_name' => $fileName
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '头像上传失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除头像
     */
    public function deleteAvatar(Request $request)
    {
        $user = $request->user();
        
        if (!$user->avatar) {
            return response()->json([
                'success' => false,
                'message' => '用户没有头像'
            ], 400);
        }

        try {
            // 删除文件
            $this->deleteOldAvatar($user->avatar);

            // 更新用户头像为空
            $user->update(['avatar' => null]);

            // 记录删除日志
            SystemLog::log(
                'delete_avatar',
                'file',
                '用户删除头像',
                $user->id,
                'User',
                $user->id,
                null,
                [],
                'info'
            );

            return response()->json([
                'success' => true,
                'message' => '头像删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '头像删除失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除旧头像文件
     */
    private function deleteOldAvatar($avatarUrl)
    {
        try {
            // 从URL中提取文件名
            $fileName = basename($avatarUrl);
            $path = 'private/avatars/' . $fileName;
            
            if (Storage::disk('local')->exists($path)) {
                Storage::disk('local')->delete($path);
            }
        } catch (\Exception $e) {
            // 记录错误但不抛出异常
            Log::error('删除旧头像失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件信息
     */
    public function getFileInfo(Request $request, $filename)
    {
        $path = 'private/avatars/' . $filename;
        
        if (!Storage::disk('local')->exists($path)) {
            return response()->json([
                'success' => false,
                'message' => '文件不存在'
            ], 404);
        }

        $fileInfo = [
            'name' => $filename,
            'size' => Storage::disk('local')->size($path),
            'mime_type' => Storage::disk('local')->mimeType($path),
            'last_modified' => Storage::disk('local')->lastModified($path),
        ];

        return response()->json([
            'success' => true,
            'data' => $fileInfo
        ]);
    }

    /**
     * 获取头像文件内容（用于显示）
     * 添加了用户权限检查，确保用户只能访问自己的头像
     */
    public function getAvatar(Request $request, $filename)
    {
        // 检查用户是否已登录
        if (!$request->user()) {
            abort(401, '未授权访问');
        }

        // 从文件名中提取用户ID
        if (!preg_match('/^avatar_(\d+)_/', $filename, $matches)) {
            abort(404, '无效的头像文件名');
        }

        $avatarUserId = (int) $matches[1];
        $currentUserId = $request->user()->id;

        // 检查用户是否只能访问自己的头像
        if ($avatarUserId !== $currentUserId) {
            abort(403, '无权访问此头像');
        }

        $path = 'private/avatars/' . $filename;
        
        if (!Storage::disk('local')->exists($path)) {
            abort(404, '头像文件不存在');
        }

        $file = Storage::disk('local')->get($path);
        $mimeType = Storage::disk('local')->mimeType($path);

        // 记录访问日志
        SystemLog::log(
            'view_avatar',
            'file',
            '用户查看头像',
            $currentUserId,
            'User',
            $currentUserId,
            null,
            ['filename' => $filename],
            'info'
        );

        return response($file, 200, [
            'Content-Type' => $mimeType,
            'Cache-Control' => 'public, max-age=31536000', // 缓存1年
        ]);
    }
}
